package com.android.common.result.contract;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class TakeCropPicture extends ActivityResultContract<CropImage, Uri> {

    private Uri mOutPutUri = null;

    @NonNull
    @Override
    public Intent createIntent(@NonNull Context context, CropImage input) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(input.inPutUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", input.aspectX);
        intent.putExtra("aspectY", input.aspectY);
        intent.putExtra("outputX", input.width);
        intent.putExtra("outputY", input.height);
        intent.putExtra("scale", true);
        //将剪切的图片保存到目标Uri中
        intent.putExtra(MediaStore.EXTRA_OUTPUT, input.outPutUri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        return intent;
    }

    @Override
    public Uri parseResult(int resultCode, @Nullable Intent intent) {
        if (intent == null || resultCode != Activity.RESULT_OK
            || mOutPutUri == null
        ) return null;

        return mOutPutUri;
    }

    public void setOutPutUri(Uri outPutUri) {
        this.mOutPutUri = outPutUri;
    }
}

